import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

public class 存储大文件 {

    @Test
    public void 存取照片() {
        Connection connection = null;
        try {
            connection = 连接.getConnection();

            String sql = "update user set photo = ? where name = '王康'";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            // 操作Blob类型的变量
            FileInputStream photo = new FileInputStream("src/source/123.png");
            preparedStatement.setBlob(1, photo);

            int i = preparedStatement.executeUpdate();
            if (i != 0) System.out.println("照片插入成功");

            sql = "select photo from user where name = '王康'";
            PreparedStatement preparedStatement1 = connection.prepareStatement(sql);

            ResultSet resultSet = preparedStatement1.executeQuery();

            if (resultSet.next()) {
                System.out.println("照片查询成功");
                Blob photo1 = resultSet.getBlob("photo");
                InputStream inputStream = photo1.getBinaryStream();
                FileOutputStream outputStream = new FileOutputStream("src/source/321.png");

                byte[] buffeer = new byte[1024];
                for (int len = inputStream.read(buffeer); len != -1; len = inputStream.read(buffeer)) {
                    outputStream.write(buffeer, 0, len);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
